(function (vc) {
    vc.extends({
        data: {
            addProductInfo: {
                shId: '',
                shName: '',
                warnStock: 20,
                productId: '',
                categoryId: '',
                prodName: '',
                prodDesc: '',
                keyword: '',
                barCode: '1',
                unitName: '',
                sort: 0,
                isPostage: '2',
                postage: '0.00',
                productCategorys: [],
                content: '',
                states: [],
                state: 2002,
                coverPhoto: '',
                carouselFigurePhoto: [],
                productSpecs: [],
                areaCode: '',
                distributionModes: [],
                hktIds: [],
                housekeepingTypes: [],
                shopHouses: []
            }
        },
        _initMethod: function () {
            vc.getDict('product', "state", function (_data) {
                $that.addProductInfo.states = _data;
            });
			$that.addProductInfo.categoryId = vc.getParam('categoryId');
            $that._initAddProduct();
            $that._listShopHouses();
            // $that._listAddHousekeepingTypes();
            $that._listAddProductCategorys();
        },
        _initEvent: function () {
            vc.on("addProduct", "notifyUploadCoverImage", function (_param) {
                if (_param.length > 0) {
                    $that.addProductInfo.coverPhoto = _param[0].url;
					// 传封面时，把轮播图也传了
					let _photos = [];
					_photos.push(_param[0].url);
					vc.emit('addProductCarouselFigure', 'uploadImageUrl', 'notifyPhotos', _photos);
                } else {
                    $that.addProductInfo.coverPhoto = '';
                }
				
            });
            vc.on("addProduct", "notifyUploadCarouselFigureImage", function (_param) {
                $that.addProductInfo.carouselFigurePhoto = [];
                _param.forEach(_p => {
                    $that.addProductInfo.carouselFigurePhoto.push(_p.url);
                });
				//console.log("carouselFigurePhoto",$that.addProductInfo.carouselFigurePhoto)
            });
        },
        methods: {
			_quickunitName(unitN){
				$that.addProductInfo.unitName =  unitN
			},
            addProductValidate() {
                return vc.validate.validate({
                    addProductInfo: $that.addProductInfo
                }, {
                    'addProductInfo.categoryId': [{
                        limit: "required",
                        param: "",
                        errInfo: "商品分组不能为空"
                    },
                    {
                        limit: "num",
                        param: "",
                        errInfo: "商品分组未选择"
                    },
                    ],
                    'addProductInfo.prodName': [{
                        limit: "required",
                        param: "",
                        errInfo: "商品名称不能为空"
                    },
                    {
                        limit: "maxLength",
                        param: "128",
                        errInfo: "商品名称不能超过128位"
                    },
                    ],
                    'addProductInfo.prodDesc': [{
                        limit: "required",
                        param: "",
                        errInfo: "商品简介不能为空"
                    },
                     {
                        limit: "maxLength",
                        param: "256",
                        errInfo: "商品简介不能超过256位"
                    },
                    ],
                    /*'addProductInfo.keyword': [{
                        limit: "required",
                        param: "",
                        errInfo: "关键词不能为空"
                    }, 
                    {
                        limit: "maxLength",
                        param: "256",
                        errInfo: "关键词不能超过256位"
                    },
                    ],*/
                    'addProductInfo.barCode': [{
                        limit: "maxLength",
                        param: "15",
                        errInfo: "产品条码不能超过15位"
                    },],
                    'addProductInfo.shId': [{
                        limit: "required",
                        param: "",
                        errInfo: "仓库不能为空"
                    },],
                    'addProductInfo.unitName': [{
                        limit: "maxLength",
                        param: "32",
                        errInfo: "单位不能超过32位"
                    },],
                    'addProductInfo.sort': [{
                        limit: "num",
                        param: "",
                        errInfo: "排序格式错误"
                    },],
                    'addProductInfo.warnStock': [{
                        limit: "num",
                        param: "",
                        errInfo: "库存警告格式错误"
                    },],
                    'addProductInfo.isPostage': [{
                        limit: "num",
                        param: "",
                        errInfo: "是否包邮格式错误"
                    },],
                    'addProductInfo.postage': [{
                        limit: "money",
                        param: "",
                        errInfo: "邮费格式错误,请填写如 3.00"
                    },]
                });
            },
            saveProductInfo: function () {
                let flag = false;
                let _productSpecs = $that.addProductInfo.productSpecs;
                for (let i = 0; i < _productSpecs.length; i++) {                    
					_productSpecs[i].deduction = _productSpecs[i].price;
					_productSpecs[i].ownerPrice = _productSpecs[i].price;
					_productSpecs[i].vipPrice = _productSpecs[i].price;
					_productSpecs[i].otPrice = _productSpecs[i].price;
					if (_productSpecs[i].isDefault == "T") {
					    flag = true;
					    break;
					}
                }
                if (!flag && _productSpecs.length > 0) {
                    vc.toast("未选择默认规格");
                    return;
                }
				$that.addProductInfo.keyword = $that.addProductInfo.prodName;//关键字没看出有什么用，先隐藏用产品名称替代，简化操作
                if (!$that.addProductValidate()) {
                    vc.toast(vc.validate.errInfo);
                    return;
                }
                $that.addProductInfo.shopId = vc.getCurrentCommunity().shopId;
                $that.addProductInfo.areaCode = vc.getCurrentCommunity().areaCode;
                vc.http.apiPost(
                    '/product.saveProduct',
                    JSON.stringify($that.addProductInfo), {
                    emulateJSON: true
                },
                    function (json, res) {
                        //vm.menus = vm.refreshMenuActive(JSON.parse(json),0);
                        let _json = JSON.parse(json);
                        if (_json.code == 0) {
                            //关闭model
                            vc.goBack();
                            vc.toast("添加成功");
                            return;
                        }
                        vc.toast(_json.msg);
                    },
                    function (errInfo, error) {
                        console.log('请求失败处理');
                        vc.toast(errInfo);
                    });
            },
            _addDistributionModes: function () {
                let param = {
                    params: {
                        page: 1,
                        row: 50,
                        shopId: vc.getCurrentCommunity().shopId
                    }
                };
                //发送get请求
                vc.http.apiGet('/distributionMode/queryDistributionMode',
                    param,
                    function (json, res) {
                        let _json = JSON.parse(json);
                        $that.addProductInfo.distributionModes = _json.data;
                    },
                    function (errInfo, error) {
                        console.log('请求失败处理');
                    }
                );
            },
            _closeAddProduct: function () {
                vc.goBack();
            },
            _listAddProductCategorys: function (_page, _rows) {
                let param = {
                    params: {
                        page: 1,
                        row: 50,
                        shopId: vc.getCurrentCommunity().shopId
                    }
                };
                //发送get请求
                vc.http.apiGet('/productCategory.queryProductCategory',
                    param,
                    function (json, res) {
                        let _json = JSON.parse(json);
                        $that.addProductInfo.productCategorys = _json.data;
                    },
                    function (errInfo, error) {
                        console.log('请求失败处理');
                    }
                );
            },
            _initAddProduct: function () {
                let $summernote = $('.summernote').summernote({
                    lang: 'zh-CN',
                    height: 300,
                    placeholder: '必填，请输入商品描述',
                    callbacks: {
                        onImageUpload: function (files, editor, $editable) {
                            $that.sendFile($summernote, files);
                        },
                        onChange: function (contents, $editable) {
                            $that.addProductInfo.content = contents;
                        }
                    },
                    toolbar: [
                        ['style', ['style']],
                        ['font', ['bold', 'italic', 'underline', 'clear']],
                        ['fontname', ['fontname']],
                        ['color', ['color']],
                        ['para', ['ul', 'ol', 'paragraph']],
                        ['height', ['height']],
                        ['table', ['table']],
                        ['insert', ['link', 'picture']],
                        ['view', ['fullscreen', 'codeview']],
                        ['help', ['help']]
                    ],
                });
            },
            sendFile: function ($summernote, files) {
                console.log('上传图片', files);
                var param = new FormData();
                param.append("uploadFile", files[0]);
                param.append('shopId', vc.getCurrentCommunity().shopId);
                vc.http.upload('/upload/uploadFile',
                    param, {
                    emulateJSON: true,
                    //添加请求头
                    headers: {
                        "Content-Type": "multipart/form-data"
                    }
                },
                    function (json, res) {
                        //vm.menus = vm.refreshMenuActive(JSON.parse(json),0);
                        if (res.status == 200) {
                            let data = JSON.parse(json);
                            //关闭model
                            $summernote.summernote('insertImage', data.data.url);
                            return;
                        }
                        vc.toast(json);
                    },
                    function (errInfo, error) {
                        console.log('请求失败处理');
                        vc.toast(errInfo);
                    });
            },
            _openAddSpecModal: function () {
				if ($that.addProductInfo.productSpecs.length > 0) {
				    vc.toast("只能添加一个规格，不同规格请另外添加商品，请在商品名称中加入规格，更吸引用户点击");
					return;
				}
                let _productSpec = {
                    specCd: "0",
                    stock: "0",
                    sales: "0",
                    price: "0.00",
                    costPrice: "0.00",
                    ownerPrice: "0.00",
                    vipPrice: "0.00",
                    otPrice: "0.00",
                    deduction: "0.00",
                    isDefault: "F",
                    barCode: ""
                }
				
                $that.addProductInfo.productSpecs.push(_productSpec);
                let _productSpecs = $that.addProductInfo.productSpecs;
                let flag = false;
                for (let i = 0; i < _productSpecs.length; i++) {
                    if (_productSpecs[i].isDefault == "T") {
                        flag = true;
                        break;
                    }
                }
                if (!flag && _productSpecs.length > 0) {
                    _productSpecs[0].isDefault = "T"
                }
				
            },
            _openAddDeleteProductSpec: function (_productSpec) {
                let _productSpecs = $that.addProductInfo.productSpecs;
                let index = _productSpecs.indexOf(_productSpec);
                if (index > -1) {
                    _productSpecs.splice(index, 1);
                }
                let flag = false;
                for (let i = 0; i < _productSpecs.length; i++) {
                    if (_productSpecs[i].isDefault == "T") {
                        flag = true;
                        break;
                    }
                }
                if (!flag && _productSpecs.length > 0) {
                    _productSpecs[0].isDefault = "T"
                }
            },
            _doAddDefaultProductSpec: function (_product, _defaultProductSpec) {
                _product.productSpecs.forEach(item => {
                    item.isDefault = "F";
                });
                _defaultProductSpec.isDefault = "T";
                $that.addProductInfo.productSpecs = JSON.parse(JSON.stringify(_product.productSpecs));
            },
            _setModeName: function (_modeId) {
                $that.addProductInfo.distributionModes.forEach(item => {
                    if ('-1' == _modeId) {
                        $that.addProductInfo.modeName = '自送';
                    } else if (item.modeId == _modeId) {
                        $that.addProductInfo.modeName = item.modeName;
                    }
                });
            },
            _changeShopHouseAdd: function (_shopHouseId) {
                $that.addProductInfo.shopHouses.forEach(item => {
                    if (item.shId == _shopHouseId) {
                        $that.addProductInfo.shName = item.shName;
                    }
                });
            },
           /* _listAddHousekeepingTypes: function (_page, _rows) {
                var param = {
                    params: {
                        page: 1,
                        row: 30,
                        typeCd: '2002',
                        shopId: '9999',
                        skipType: '3'
                    }
                };
                //发送get请求
                vc.http.apiGet('/housekeepingType.queryHousekeepingType',
                    param,
                    function (json, res) {
                        let _json = JSON.parse(json);
                        $that.addProductInfo.housekeepingTypes = _json.data;

                    }, function (errInfo, error) {
                        console.log('请求失败处理');
                    }
                );
            }, */
            _listShopHouses: function (_page, _rows) {
                let param = {
                    params: {
                        page: 1,
                        row: 100,
                        shopId: vc.getCurrentCommunity().shopId
                    }
                };
                //发送get请求
                vc.http.apiGet('/shopHouse.queryShopHouse',
                    param,
                    function (json, res) {
                        let _json = JSON.parse(json);
                        $that.addProductInfo.shopHouses = _json.data;
                    }, function (errInfo, error) {
                        console.log('请求失败处理');
                    }
                );
            },
        }
    });
})(window.vc);